<template>
  <el-select  multiple collapse-tags 
              :value="defaultValue" :clearable="isAll" :disabled="disabled" @change="handleChange" style="width:100%">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.name"
      :value="item.code"
      :disabled="item.disabled">
    </el-option>
  </el-select>
</template>
<script>
import { getOptions } from '@/api/common'
export default {
  // 多选下拉框
  name: 'multipleCombox',
  data() {
    return {
      options: [],
      defaultValue: []
    }
  },
  props: {
    codeType: {
      type: String,
      required: true
    },
    isAll: {
      type: Boolean,
      default: function() {
        return true
      }
    },
    disabledValues: {
      type: Array
    },
    value: {
      type: Array
    },
    disabled: {
      type: Boolean
    }

  },
  methods: {
    handleChange(val) {
      this.$emit('input', val)
    },
    init() {
      getOptions(this.codeType, this.isAll).then(response => {
        const data = response.data.data
        if (data) {
          const tmp = []
          const supportType = []

          data.forEach(element => {
            const elementTmp = element
            elementTmp.disabled = this.disabledValues && this.disabledValues.indexOf(element.code) !== -1
            tmp.push(elementTmp)
            if (elementTmp.disabled === false || !elementTmp.disabled) {
              supportType.push(element)
            }
          })

          this.options = tmp
          if (!this.isAll) {
            if (supportType.length > 0) {
              this.defaultValue = this.value || [supportType[0].code]
              this.$emit('input', this.defaultValue)
            }
          }
        }
      })
    }
  },
  created() {
    this.defaultValue = this.value
    this.init()
  },
  watch: {
    // disabledValues() {
    //   if (this.options.length > 0) {
    //     const tmp = []
    //     const supportType = []
    //     this.options.forEach(element => {
    //       const elementTmp = element
    //       elementTmp.disabled = this.disabledValues && this.disabledValues.indexOf(element.code) !== -1
    //       tmp.push(elementTmp)
    //       if (elementTmp.disabled === false || !elementTmp.disabled) {
    //         supportType.push(element)
    //       }
    //     })
    //     this.defaultValue = (this.disabledValues.indexOf(this.value) === -1 && supportType.length > 0) ? this.value : supportType[0].code
    //     this.$emit('input', this.defaultValue)
    //   }
    // },
    value() {
      this.defaultValue = this.value
    },
    codeType() {
      this.init()
    }
  }
}
</script>
